package com.cxyd.modules.wms.excel.listener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.cxyd.common.exception.RootException;
import com.cxyd.common.utils.ConvertUtils;
import com.cxyd.modules.wms.dao.PurchaseDao;
import com.cxyd.modules.wms.dao.PurchaseDetailDao;
import com.cxyd.modules.wms.dto.PurchaseDTO;
import com.cxyd.modules.wms.dto.PurchaseDetailDTO;
import com.cxyd.modules.wms.dto.SupplierDTO;
import com.cxyd.modules.wms.entity.PurchaseEntity;
import com.cxyd.modules.wms.entity.SpuEntity;
import com.cxyd.modules.wms.excel.easy.PurchaseEasyExcel;
import com.cxyd.modules.wms.service.PurchaseDetailService;
import com.cxyd.modules.wms.service.PurchaseService;
import com.cxyd.modules.wms.service.SpuService;
import com.cxyd.modules.wms.service.SupplierService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class PurchaseExcelListener extends AnalysisEventListener<PurchaseEasyExcel> {

    private static final Logger logger = LoggerFactory.getLogger(PurchaseExcelListener.class);

    private final PurchaseService purchaseService;
    private final PurchaseDetailService purchaseDetailService;
    private final SpuService spuService;

    private static final int BATCH_COUNT = 1;
    private List<PurchaseEasyExcel> cache = new ArrayList<>(BATCH_COUNT);
    private int total = 0;
    private PurchaseDTO purchase = new PurchaseDTO();

    public PurchaseExcelListener(PurchaseService purchaseService, PurchaseDetailService purchaseDetailService, SpuService spuService) {
        this.purchaseService = purchaseService;
        this.purchaseDetailService = purchaseDetailService;
        this.spuService = spuService;
    }

    @Override
    public void invoke(PurchaseEasyExcel purchaseEasyExcel, AnalysisContext analysisContext) {
        cache.add(purchaseEasyExcel);
        if (total == 0) {
            savePurchase();
        }
        if (cache.size() >= BATCH_COUNT) {
            saveDetail();
            cache.clear();
        }
        total++;
    }

    private void savePurchase() {
        PurchaseEasyExcel purchaseEasyExcel = cache.get(0);
        if (StrUtil.isEmpty(purchaseEasyExcel.getDeliverNo())) {
            throw new RootException("收货单号不可为空！");
        }
        if (StrUtil.isEmpty(purchaseEasyExcel.getSupplierName())) {
            throw new RootException("供货方不可为空！");
        }
        PurchaseEntity insertPurchase = new PurchaseEntity();
        insertPurchase.setPurchaseNo("IN#" + purchaseEasyExcel.getDeliverNo());
        insertPurchase.setDeliverNo(purchaseEasyExcel.getDeliverNo());
        // 采购收货
        insertPurchase.setPurchaseType("采购入库");
        insertPurchase.setBelongSystem("EXCEL");
        insertPurchase.setSupplierName(purchaseEasyExcel.getSupplierName());
        insertPurchase.setDeliverAddress(purchaseEasyExcel.getDeliverAddress());
        insertPurchase.setPurchaseSt(0);
        purchaseService.insert(insertPurchase);
        purchase = ConvertUtils.sourceToTarget(insertPurchase, PurchaseDTO.class);
    }

    private void saveDetail() {
        for (PurchaseEasyExcel excel : cache) {
            if (StrUtil.isEmpty(excel.getSpuNo())) {
                throw new RootException("物料编号不可为空！");
            }
            if (excel.getPlanQty().compareTo(BigDecimal.ZERO) <= 0) {
                throw new RootException("数量必须大于0！");
            }
            String spuNo = excel.getSpuNo();
            SpuEntity spuEntity = spuService.findBySpuNo(spuNo);
            if (ObjectUtils.isEmpty(spuEntity)) {
                throw new RootException("物料【" + spuNo + "】未在系统中维护!请检查");
            }
            PurchaseDetailDTO insertDetail = new PurchaseDetailDTO();
            insertDetail.setPurchaseId(purchase.getPurchaseId());
            insertDetail.setDeliverNo(purchase.getDeliverNo());
            insertDetail.setEbeln(excel.getEbeln());
            insertDetail.setEbelp(excel.getEbelp());
            insertDetail.setIntrovertedNo(excel.getIntrovertedNo());
            insertDetail.setSpuNo(spuNo);
            insertDetail.setSpuName(spuEntity.getSpuName());
            insertDetail.setPlanQty(excel.getPlanQty());
            insertDetail.setDetailSt(0);
            insertDetail.setComments(excel.getComments());
            purchaseDetailService.save(insertDetail);
        }
        cache.clear();
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveDetail();
        cache.clear();
        logger.info("入库单处理完成 count={}", total);
    }
}
